package com.hand.wfive.loginAndVip;

import android.content.Context;

import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WechatLogin {

    private static WechatLogin sWechatLogin;
    private final IWXAPI mWXApi;
    private WechatLoginResultCallBack callBack;


    public WechatLogin(Context context, String wxAppid) {
        mWXApi = WXAPIFactory.createWXAPI(context, null);
        mWXApi.registerApp(wxAppid);
    }

    public static void init(Context context, String wxAppid) {
        if (sWechatLogin == null) {
            sWechatLogin = new WechatLogin(context, wxAppid);
        }
    }

    public static WechatLogin getInstance() {
        return sWechatLogin;
    }

    public void wechatLogin(WechatLoginResultCallBack callBack) {
        this.callBack = callBack;
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        mWXApi.sendReq(req);
    }

    public void onResp(BaseResp resp) {
        if (BaseResp.ErrCode.ERR_OK == resp.errCode) {
            SendAuth.Resp authResp = (SendAuth.Resp) resp;
            final String code = authResp.code;
            callBack.onSuccess(code);
        } else {
            if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                callBack.onCancel();
                return;
            }
            callBack.onError();
        }
    }


    /**
     * 支付结果回调
     */
    public interface WechatLoginResultCallBack {
        void onSuccess(String code);

        void onError();

        void onCancel();
    }

}
